package main

import "fmt"

type Student struct {
	Name string
	next *Student
}

// 遍历链表的方法
func trans(p *Student) {
	for p != nil {
		fmt.Println(*p)
		p = p.next
	}
}

// 头插法，从左边插入
// 每个新加入的元素都插入到头部元素的后面，这样的好处是头部元素的地址不变
func CreateLinkListLeft(p *Student) {
	var head = p
	for i := 0; i < 10; i++ {
		p := Student{
			Name: fmt.Sprintf("stuL%d", i),
		}
		p.next = head.next
		head.next = &p
	}
}

// 尾插法，从右边加入
func CreateLinkListRight(p *Student) {
	var tail = p
	for i := 0; i < 10; i++ {
		p := Student{
			Name: fmt.Sprintf("stuR%d", i),
		}
		tail.next = &p
		tail = &p
	}
}

func main() {
	var headL Student
	fmt.Println("头插法")
	CreateLinkListLeft(&headL)  // 结构体是值类型，要改变里面的值，就是传指针
	trans(&headL)

	var headR Student
	fmt.Println("尾插法")
	CreateLinkListRight(&headR)
	trans(&headR)
}

